package com.itlaobing.dataaccess.handler;

import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDate;
import java.util.Objects;

public class LocalDateHandler implements TypeHandler<LocalDate> {

    @Override
    public void setParameter(PreparedStatement ps, int index, LocalDate localDate, JdbcType jdbcType) throws SQLException {
        java.sql.Date date = null ;
        if( Objects.nonNull( localDate ) ) {
            date = java.sql.Date.valueOf( localDate );
        }
        ps.setDate( index , date ); // 设置 指定位置 (index) 的 参数值 (date)
    }

    @Override
    public LocalDate getResult( ResultSet rs , String label ) throws SQLException {
        LocalDate localDate = null ;
        java.sql.Date date = rs.getDate( label );
        if( Objects.nonNull( date ) ) {
            localDate = date.toLocalDate();
        }
        return localDate;
    }

    @Override
    public LocalDate getResult( ResultSet rs , int index ) throws SQLException {
        LocalDate localDate = null ;
        java.sql.Date date = rs.getDate( index );
        if( Objects.nonNull( date ) ) {
            localDate = date.toLocalDate();
        }
        return localDate;
    }

    @Override
    public LocalDate getResult( CallableStatement cs , int index ) throws SQLException {
        LocalDate localDate = null ;
        java.sql.Date date = cs.getDate( index ) ;
        if( Objects.nonNull( date ) ) {
            localDate = date.toLocalDate();
        }
        return localDate;
    }

}
